package com.gdkm.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.gdkm.dao.BlogDao;
import com.gdkm.daomain.Blog;
import com.gdkm.util.FileUploadUtils;

public class BlogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf8");
		request.setCharacterEncoding("utf8");
		BlogDao blogDao = new BlogDao();
		String op = request.getParameter("op");
		// 新增博客
		if (op != null && op.equals("addBlog")) {
			Blog blog = new Blog();
			Map<String, String> map = new HashMap<String, String>();
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			// 设置临时文件存储位置，如果文件大小大于设置临界值，则使用setRepository()以临时文件保存、
			dfif.setRepository(new File(this.getServletContext().getRealPath("/upload")));
			// 设置上传文件缓存大小为10m
			dfif.setSizeThreshold(1024 * 1024 * 10);
			// 创建上传组件
			ServletFileUpload upload = new ServletFileUpload(dfif);
			// 处理上传文件乱码
			upload.setHeaderEncoding("utf-8");
			try {
				List<FileItem> items=upload.parseRequest(request);
				for(FileItem item:items){
					//判断当前是否为上传组件
					if(item.isFormField()){
						//不是上传组件，获取普通文本框的name和value
						String fieldName=item.getFieldName();//获取组建名称
						String value=item.getString("utf-8");//解决上传乱码问题
						System.out.println(fieldName+"="+value);
						map.put(fieldName, value);
					}else{
						//是上传组件
						//得到上传的文件真实名称
						String fileName=item.getName();
						fileName=FileUploadUtils.subFileName(fileName);
						//得到随机名称
						String randomName=FileUploadUtils.generateRandonFileName(fileName);
						//得到随机目录
						String randomDir=FileUploadUtils.generateRandomDir(randomName);
						//图片存储父目录
						String imgurl_parent="/blogImg"+randomDir;
						File parentDIr=new File(this.getServletContext().getRealPath(imgurl_parent));
						if(!parentDIr.exists()){
							parentDIr.mkdir();
						}
						String imgurl=imgurl_parent+"/"+randomName;
						map.put(imgurl, imgurl);
						IOUtils.copy(item.getInputStream(), new FileOutputStream(new File(parentDIr,randomName)));
						item.delete();
					}
				}
			} catch (FileUploadException e) {
				
				e.printStackTrace();
			}
			try {
				BeanUtils.populate(blog, map);
				blog.setNum(0);
				blog.setPraise(0);
				System.out.println(blog);
				blogDao.addBlog(blog);
				request.getRequestDispatcher("/manager/BlogServlet?op=listBlog").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("msg", "新增失败");
				request.getRequestDispatcher("/manager/addBlog.jsp").forward(request, response);
			}
			
		}
		
		
		//查询所有博客
		else if(op!=null && op.equals("listBlog")){
			try {
				List<Blog> listBlog=blogDao.findAllBlog();
				request.setAttribute("listBlog", listBlog);
				request.getRequestDispatcher("/manager/listBlog.jsp").forward(request, response);
				
			} catch (SQLException e) {
				e.printStackTrace();
				response.getWriter().write("系统异常"+e.getMessage());
			}
		}
		//查看博客
		else if(op!=null && op.equals("viewBlog")){
			try {
				int id =Integer.parseInt(request.getParameter("id"));
				Blog blog =blogDao.findBlogById(id);
				System.out.println(blog);
				request.setAttribute("blog", blog);
				request.getRequestDispatcher("/manager/viewBlog.jsp").forward(request, response);	
				
			} catch (SQLException e) {
				e.printStackTrace();
				response.getWriter().write("系统异常"+e.getMessage());
			}	
			
		}
		//按照id删除博客
		else if(op!=null && op.equals("deleteBlog")){
			int id=Integer.parseInt(request.getParameter("id"));
			try {
				blogDao.deleteBlog(id);
				request.getRequestDispatcher("/manager/BlogServlet?op=listBlog").forward(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		
	}

}
